using System.Collections;
using Holoville.HOTween;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PrivateCarManager : MonoBehaviour
{
	public static PrivateCarManager instance;

	public UISprite sprIndicator;

	private LayerMask collisionGround;

	public GameObject privateCarRespawn;

	public GameObject pointerSpawnCar;

	public GameObject pointerSpawnTank;

	public float _culldownCar = 30f;

	public float _culldownMoto = 10f;

	public float _culldownTank = 100f;

	private EntityBehavior _tempCar;

	public bool _activeBut = true;

	private PositionCar temp;

	public CarSlot[] slots;

	private Coroutine findCurrentCar;

	private string equipCar = string.Empty;

	private string specialCarName = string.Empty;

	private IEnumerator wait;

	public EntityBehavior currentCar
	{
		get
		{
			return (slots.Length != 0) ? slots[0].car : null;
		}
		set
		{
			slots[0].SetNewCar(value);
		}
	}

	public float culldown
	{
		get
		{
			switch (MarketController.Instance.GetProduct(equipCar).subCategoryName)
			{
			case "Bikes":
				return _culldownMoto;
			case "Cars":
				return _culldownCar;
			case "Tanks":
				return _culldownTank;
			default:
				return 10f;
			}
		}
		set
		{
			_culldownCar = value;
			_culldownMoto = value;
			_culldownTank = value;
		}
	}

	private void Awake()
	{
		instance = this;
		if (Application.loadedLevelName != "Lobby")
		{
			HOTween.Init();
			slots = new CarSlot[1];
			GameObject gameObject = new GameObject();
			gameObject.name = "Car";
			slots[0] = gameObject.AddComponent<CarSlot>();
			slots[0].SetNewCar(null);
		}
	}

	private void OnDestroy()
	{
		instance = null;
	}

	private void Start()
	{
		if (Application.loadedLevelName != "Lobby")
		{
			if (GameController.instance != null)
			{
				collisionGround = GameController.instance.collisionGround;
			}
			if (GameTopWindow.instance != null)
			{
				sprIndicator = GameTopWindow.instance.sprIndicator;
			}
			if (GameController.instance.curTypeGame != TypeGame.race && GameController.instance.curTypeGame != TypeGame.tanks && GameController.instance.curTypeGame != TypeGame.RocketLeague)
			{
				FindCurrentCar();
			}
			if (GameController.instance.curTypeGame == TypeGame.tanks || GameController.instance.curTypeGame == TypeGame.RocketLeague || GameController.instance.curTypeGame == TypeGame.WalkingRobots)
			{
				culldown = 0f;
			}
		}
	}

	public void FindCurrentCar(bool unequip = false)
	{
		if (findCurrentCar != null)
		{
			StopCoroutine(findCurrentCar);
		}
		findCurrentCar = StartCoroutine(FindCurrentCarCoroutine(unequip));
	}

	private IEnumerator FindCurrentCarCoroutine(bool unequip)
	{
		if (GameController.instance != null && GameController.instance.currentMapType == mapType.Small)
		{
			yield break;
		}
		if (unequip)
		{
			UnEquipCar();
		}
		if (currentCar == null)
		{
			CarInstantiate(string.Empty);
		}
		else if (currentCar.playersCount > 0)
		{
			currentCar.AddEventListener(this, "EndGetOut", delegate
			{
				StartCoroutine(DestroyEquipedCar());
			});
			GameController.instance.playerScript.GetOutOfCar(true);
			yield return null;
		}
		else if (currentCar != null)
		{
			StartCoroutine(DestroyEquipedCar());
		}
		else
		{
			yield return new WaitForSeconds(0.2f);
			CarInstantiate(string.Empty);
		}
	}

	public IEnumerator DestroyEquipedCar()
	{
		if (currentCar.isDestroying)
		{
			yield return null;
		}
		if (settings.offlineMode)
		{
			Object.Destroy(currentCar.gameObject);
		}
		else
		{
			yield return new WaitForSeconds(0.5f);
			PhotonNetwork.Destroy(currentCar.gameObject);
		}
		yield return null;
		CarInstantiate(string.Empty);
	}

	public void UnEquipCar()
	{
		if (PointerController.instance != null && currentCar != null)
		{
			PointerController.instance.RemovePointer(currentCar.transform);
		}
		if (!(currentCar != null))
		{
			return;
		}
		if (typeof(CarBehavior) == currentCar.GetType() || typeof(MotoBehavior) == currentCar.GetType())
		{
			((CarBehavior)currentCar).RemoveFromList();
		}
		if (currentCar.isFree)
		{
			if (settings.offlineMode || SceneManager.GetActiveScene().name.Equals("Lobby"))
			{
				Object.Destroy(currentCar.gameObject);
			}
			else
			{
				PhotonNetwork.RemoveRPCs(currentCar.photonView);
				PhotonNetwork.Destroy(currentCar.gameObject);
			}
			currentCar = null;
		}
	}

	public void CarInstantiate(string name = "", bool specialCar = false)
	{
		if (!name.Equals(string.Empty))
		{
			if (specialCar)
			{
				specialCarName = name;
			}
			else
			{
				equipCar = name;
			}
		}
		else
		{
			if (specialCar)
			{
				BCWDebug.LogError("You must specify what special car to instantiate!");
				return;
			}
			equipCar = Load.LoadString("car");
		}
		if (currentCar != null)
		{
			if (settings.offlineMode)
			{
				Object.Destroy(currentCar.gameObject);
			}
			else
			{
				PhotonNetwork.Destroy(currentCar.gameObject);
			}
		}
		string text = ((!specialCar) ? equipCar : specialCarName);
		if (!text.Equals(string.Empty))
		{
			if (SceneManager.GetActiveScene().name == "Lobby")
			{
				return;
			}
			if (settings.offlineMode)
			{
				Object original = Resources.Load("Cars/PrivateCars/" + text);
				currentCar = ((GameObject)Object.Instantiate(original, Vector3.down * 1000f, Quaternion.identity)).GetComponent<EntityBehavior>();
			}
			else
			{
				currentCar = PhotonNetwork.Instantiate("Cars/PrivateCars/" + text, Vector3.down * 1000f, Quaternion.identity, 0).GetComponent<EntityBehavior>();
				UpdatePrivateCarProps(Vector3.down * 1000f, Quaternion.identity, currentCar.photonView.viewID);
			}
			currentCar.justInstantiated = true;
			if (currentCar is TitanBehavior)
			{
				TitanSpawner.instance.currentTitan = currentCar as TitanBehavior;
			}
			if (name != string.Empty && GameController.instance.curTypeGame != TypeGame.tanks)
			{
				currentCar.isImmortal = true;
			}
			currentCar.transform.parent = base.transform;
		}
		_activeBut = wait == null;
		if (currentCar != null)
		{
			currentCar.enabled = false;
			currentCar.ActivateCar(false);
			currentCar.ApplyCarUpgradesRPC(text);
			currentCar.health = currentCar.maxHealth;
			currentCar.name = text;
			if (currentCar.lerpScript != null)
			{
				currentCar.lerpScript.incrementHealth++;
			}
		}
	}

	public void UpdatePrivateCarProps(Vector3 pos, Quaternion rot, int viewId)
	{
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.hasCar, true);
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.privateCarPosition, pos);
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.privateCarRotation, rot);
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.privateCarId, viewId);
	}

	public bool CallCar(SpawnPointChief.SpawnPoint respawnPoint, bool setPointer = true, bool specialCar = false)
	{
		return CallCar(respawnPoint.position, respawnPoint.rotation, setPointer, specialCar);
	}

	public bool CallCar(Transform respawnTransform = null, bool setPointer = true, bool specialCar = false)
	{
		if (respawnTransform != null)
		{
			return CallCar(respawnTransform.position, respawnTransform.rotation, setPointer, specialCar);
		}
		return CallCar(Vector3.zero, Quaternion.identity, setPointer, specialCar);
	}

	public bool CallCar(Vector3 spawnPosition, Quaternion spawnRotation, bool setPointer, bool specialCar = false)
	{
		string text = ((!specialCar) ? equipCar : specialCarName);
		if (currentCar == null || currentCar.name != text)
		{
			CarInstantiate(text, specialCar);
		}
		if (currentCar == null)
		{
			return false;
		}
		if (_activeBut || GameController.instance.curTypeGame == TypeGame.race || specialCar)
		{
			if (!_activeBut)
			{
				BCWDebug.LogError("_activeBut == null");
			}
			currentCar.justInstantiated = false;
			currentCar.setIconMiniMap(false);
			if (settings.offlineMode)
			{
				currentCar.reset();
			}
			else
			{
				currentCar.reset();
				currentCar.photonView.RPC("reset", PhotonTargets.Others);
			}
			UpdatePrivateCarProps(spawnPosition, spawnRotation, currentCar.viewId);
			currentCar.gameObject.SetActive(true);
			PositionCar positionCar = default(PositionCar);
			if (currentCar is TitanBehavior)
			{
				positionCar = TitanSpawner.instance.titanSpawnPosition;
				spawnPosition = positionCar.pos;
				spawnRotation = positionCar.rot;
			}
			else if (spawnPosition == Vector3.zero)
			{
				positionCar = FindRespawnPointNearPlayer();
			}
			else
			{
				positionCar.pos = spawnPosition;
				positionCar.rot = spawnRotation;
			}
			RaycastHit hitInfo = default(RaycastHit);
			if (spawnPosition != Vector3.zero || Physics.Raycast(positionCar.pos + Vector3.up * 2f, Vector3.down, out hitInfo, 5f, collisionGround))
			{
				if (spawnPosition == Vector3.zero)
				{
					positionCar.pos = hitInfo.point;
				}
				if (positionCar.pos != Vector3.zero)
				{
					if (currentCar.trailer != null)
					{
						currentCar.trailer.transform.localPosition = Vector3.zero;
						currentCar.trailer.transform.localRotation = Quaternion.identity;
					}
					currentCar.transform.position = positionCar.pos;
					currentCar.transform.rotation = positionCar.rot;
					if (currentCar is CarBehavior)
					{
						currentCar.GetComponent<CarBehavior>().RCCcar.ResetTrailers();
					}
					currentCar.gameObject.SetActive(true);
					currentCar.EnablePrivatCar();
					if (currentCar is TitanBehavior)
					{
						if (GameController.instance.curTypeGame == TypeGame.WalkingRobots)
						{
							((TitanBehavior)currentCar).SpawnTitanImmediately();
						}
						else
						{
							((TitanBehavior)currentCar).SpawnTitanAnimations();
						}
					}
					else if (setPointer && PointerController.instance != null)
					{
						PointerController.instance.AddPointer(currentCar.transform, 0f);
					}
					if (!settings.offlineMode)
					{
						UpdatePrivateCarProps(positionCar.pos, positionCar.rot, currentCar.photonView.viewID);
						currentCar.photonView.RPC("SetPrivateCarPosition", PhotonTargets.Others, positionCar.pos, positionCar.rot);
					}
					if (specialCar)
					{
						return true;
					}
					_activeBut = false;
					if (wait != null)
					{
						StopCoroutine(wait);
					}
					wait = Wait();
					StartCoroutine(wait);
					return true;
				}
			}
			BCWDebug.Log("Если титан заспаунился в жопе и падает, то вот лог с позицией. Hit == null is " + hitInfo == ". Position = " + spawnPosition);
		}
		return false;
	}

	private IEnumerator Wait()
	{
		yield return new WaitForSeconds(culldown);
		ResetCarButton();
	}

	public void ResetCarButton()
	{
		_activeBut = true;
		wait = null;
		CarSlot[] array = slots;
		foreach (CarSlot carSlot in array)
		{
			carSlot.StopAnimation();
		}
	}

	public PositionCar FindRespawnPointNearPlayer()
	{
		float num = 3000f;
		float num2 = 0f;
		foreach (PositionCar item in PrivateCarRespawnPoint.instance.listCarRespawn)
		{
			if (CheckForEnemiesNearPoint(item) && CheckForCarsNearPoint(item) && CheckForPlayersNearPoint(item))
			{
				num2 = Vector3.Distance(item.pos, GameController.instance.playerScript.transform.position);
				if (num2 < num)
				{
					temp = item;
					num = num2;
				}
			}
		}
		return temp;
	}

	private bool CheckForEnemiesNearPoint(PositionCar obj)
	{
		if (MobSpawnController.instance != null && MobSpawnController.instance.MobsList.Count > 0)
		{
			EnemyBehavior[] array = MobSpawnController.instance.MobsList.ToArray();
			EnemyBehavior[] array2 = array;
			foreach (EnemyBehavior enemyBehavior in array2)
			{
				if (Vector3.Distance(obj.pos, enemyBehavior.transform.position) < 1f)
				{
					return false;
				}
			}
		}
		return true;
	}

	private bool CheckForCarsNearPoint(PositionCar obj)
	{
		foreach (EntityBehavior item in GameController.instance.arrAllCar)
		{
			if ((bool)item && Vector3.Distance(obj.pos, item.transform.position) < 5f)
			{
				return false;
			}
		}
		return true;
	}

	private bool CheckForPlayersNearPoint(PositionCar obj)
	{
		foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
		{
			if (Vector3.Distance(listPlayer.transform.position, obj.pos) < 4f)
			{
				return false;
			}
		}
		return true;
	}
}
